﻿using System;
using Csla;
using BizControl.Library.BusinessObjects.Activities;
using BizControl.DalLinq;
using BizControl.Resources;
using System.Linq;

namespace BizControl.Library.BusinessObjects.Marks
{
  [Serializable()]
  public class MarkDetails : BusinessListBase<MarkDetails, MarkDetailBO>
  {
    #region  Business Methods

    private MarkInfo _mark;

    public MarkDetailBO AddMarkDetail()
    {
      MarkDetailBO markDetail = MarkDetailBO.NewMarkDetail(_mark);
      this.Add(markDetail);
      return markDetail;
    }

    public void Remove(string name)
    {
      foreach (MarkDetailBO detail in this)
      {
        if (detail.Name == name)
        {
          Remove(detail);
          break;
        }
      }
    }

    #endregion

    #region  Factory Methods

    internal static MarkDetails NewMarkDetails(MarkInfo mark)
    {
      return DataPortal.CreateChild<MarkDetails>(mark);
    }

    internal static MarkDetails GetMarkDetails(MarkDetail[] data, MarkInfo mark)
    {
      return DataPortal.FetchChild<MarkDetails>(data, mark);
    }

    internal static MarkDetails CopyDetails(ActivityMarkBO newMark, ActivityMarkBO sourceMark)
    {
      var newDetails = DataPortal.CreateChild<MarkDetails>(new MarkInfo(newMark));
      foreach (var detail in sourceMark.Details)
      {
        var newDetail = newDetails.AddMarkDetail();
        newDetail.Name = detail.Name;
        newDetail.Value = detail.Value;
        newDetail.DetailType = detail.DetailType;
      }
      return newDetails;
    }

    private MarkDetails()
    { /* require use of factory methods */ }

    #endregion

    #region  Data Access

    private void Child_Create(MarkInfo mark)
    {
      if (null == mark) throw new ArgumentNullException(ExceptionsMessages.MarkNullReference);
      _mark = mark;
    }

    private void Child_Fetch(MarkDetail[] data, MarkInfo mark)
    {
      if (null == mark) throw new ArgumentNullException(ExceptionsMessages.MarkNullReference);
      _mark = mark;
      if (data == null) return;
      this.RaiseListChangedEvents = false;
      foreach (var child in data)
        Add(MarkDetailBO.GetMarkDetail(child, _mark));
      this.RaiseListChangedEvents = true;
    }

    #endregion
  }
}
